package com.wr;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * JUC版线程通信
 * 指定线程唤醒和等待
 * A执行完调用B，B——》C
 */
public class Demo3JUC  {

    public static void main(String[] args) {
        Test3 test = new Test3();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    test.printA();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        },"A").start();

        new Thread(()->{

            for (int i = 0; i < 10; i++) {
                try {
                    test.printB();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    test.printC();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();

    }
}

// number=1 A执行  2B执行  3C执行
class Test3 {
    private int number = 1;
    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    public  void printA() throws InterruptedException {
        lock.lock();
        try {
            while (number != 1) {
                condition1.await();
            }
            number = 2;
            System.out.println(Thread.currentThread().getName() + "--->" +"AAAAAAAAAAA");
            // 唤醒其他线程
            condition2.signal();
        } finally {
            lock.unlock();
        }

    }

    public  void printB() throws InterruptedException {
        lock.lock();
        try {
            while (number != 2) {
                condition2.await();
            }
            number = 3;
            System.out.println(Thread.currentThread().getName() + "--->" +"BBBBBBBBBB");
            // 唤醒其他线程
            condition3.signal();
        } finally {
            lock.unlock();
        }
    }

    public  void printC() throws InterruptedException {
        lock.lock();
        try {
            while (number != 3) {
                condition3.await();
            }
            number = 1;
            System.out.println(Thread.currentThread().getName() + "--->" +"CCCCCCCCCCCC");
            // 唤醒其他线程
            condition1.signal();
        } finally {
            lock.unlock();
        }
    }
}
